package cpt202.project.service.impl;

import cpt202.project.dao.UserMapper;
import cpt202.project.entity.User;
import cpt202.project.service.UserService;
import cpt202.project.service.exception.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceimpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public User login(String email, String password) {
        //根据邮箱查询用户是否存在
        User result = userMapper.findUserName(email);
        if(result==null){
            throw new UserNotExistException("用户不存在");
        }
        else{
            String correctpsw = userMapper.getpassword(email);
            if(!correctpsw.equals(password)){
                throw new PwdIncorrectException("密码错误");
            }
            else {
                return new User(result.getEmail(),null);//减轻数据体量
            }
        }
    }

    @Override
    public void Register(User user) {
        String username = user.getEmail();
        //先调用RegisterMapper中的方法判断邮箱是否被注册过
        User result = userMapper.findUserName(username);
        if (result!=null){
            //抛异常
            throw new EmailDuplicatedException("邮箱已被注册");
        }
        else{
            Integer rows = userMapper.insert(user);
            userMapper.insertdefaultbook(user.getEmail());
            //在用户注册的过程中发生异常导致插入失败
            if(rows!=1)
                throw new InsertException();
        }
    }

    @Override
    public void resetpsw(String email, String password) {
        User result = userMapper.findUserName(email);
        if(result==null)
            throw new UserNotExistException("用户不存在");
        else{
            Integer row = userMapper.updatePwdByemail(email,password);
            if(row!=1){
                throw new updateException("更新数据时发生未知异常");
            }}

    }
}
